package htmlmake;

import java.io.*;
import java.util.*;

/**
 *
 * @author eric2ai
 */
 
class HtNameComparator implements Comparator<HtDir>{
	public int compare(HtDir emp1, HtDir emp2){
		if (emp1 == null ) return 1;
		else if (emp2 == null ) return -1;
		else {
			return emp1.name.compareToIgnoreCase(emp2.name);
		}
	}
}

class HtScoreComparator implements Comparator<HtDir>{
	public int compare(HtDir emp1, HtDir emp2){
		if (emp1 == null ) return 1;
		else if (emp2 == null ) return -1;
		else {
			return emp2.score - emp1.score;
		}
	}
}

interface HtDirGetIt{
    public char getType(HtDir o);
    public String getFileName(HtDir o);
	public String getTypeString(HtDir o);
}

class HtDirGetItName implements HtDirGetIt{
    public char getType(HtDir o){
		return o.getNameType();
    }
    public String getFileName(HtDir o){
        return o.getNameFileName();
    }
	public String getTypeString(HtDir o){
		return o.getNameTypeString();
	}	
}

class HtDirGetItScore implements HtDirGetIt{
    public char getType(HtDir o){
        return o.getScoreType();
    }
    public String getFileName(HtDir o){
        return o.getScoreFileName();
    }
	public String getTypeString(HtDir o){
		return o.getScoreTypeString();
	}
}

public class HtDirList {
	static final String htDirName = "_html";
	
	public String rootDir;
	public HtDir htDirs[] = new HtDir[3000];
	public int folderNumber;
	public int noThumbFolderNumber;
	
	public void sortByName(){
		Arrays.sort(htDirs, new HtNameComparator());
	}
	
	public void sortByScore(){
		Arrays.sort(htDirs, new HtScoreComparator());
	}	

	void write1stLine(BufferedWriter out, HtDir hd) throws IOException
	{
		out.write("<td><p align=\"center\"><a href=\"..\\" + hd.dir + "\""
			//+	" target=\"_piclist\""
			+ "><img name=\"_thumb\" src=\"..\\" + hd.dir
			+ "\\_thumb.jpg\"></a></p></td>\n");		
	}

	void write2ndLine(BufferedWriter out, HtDir hd) throws IOException
	{
		out.write("<td valign=\"top\"><p align=\"left\"><span class=\"hm_thumb_score\"><a href=\""+hd.getScoreFileName()+"\">"+
			hd.getScoreTypeString()+"</a></span><span class=\"hm_thumb_weight\">&nbsp;("+hd.weight+")</span><br>");
		
		
		out.write("<span class=\"hm_thumb_desc\"><a href=\"" +
			hd.getNameFileName()+"\">"+hd.getNameType()+"</a>");
			
		if ( Character.isLetter(hd.getNameType()) ){
			out.write(hd.name.substring(1));
		} else{
			out.write(hd.name);
		}

		out.write("</span></p></td>\n");
	}
	
	void write2ndLines(BufferedWriter out, int last, int num) throws IOException
	{
		out.write("</tr><tr>\n");
		for (int j=last-num; j<last; j++){
			write2ndLine(out, htDirs[j]);
		}
		out.write("</tr>");
	}
	
	void writeFootAndClose(BufferedWriter out, int last, int num) throws IOException
	{
		if ( num != 0 ){
			write2ndLines(out, last, num);
		}
		out.write("</table></body></html>\n");
		out.close();
	}
		
	void writeHeader(BufferedWriter out, HtDir hd, HtDirGetIt getIt) throws IOException
	{
		out.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=big5\">\n");
		out.write("<meta name=\"GENERATOR\" content=\"htmlmake\">\n");
		out.write("<xml id=info></xml>\n");
		out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"hmake.css\" />\n");
		out.write("</head><body><div id=\"dHTMLToolTip\"></div><span CLASS=\"hm_title\">");
		out.write(new Date().toString() + " [" + folderNumber + "]</span><BR>");
		out.write("<p><a name=00><span class=\"hm_assort_name\"> /" + getIt.getTypeString(hd) + "/ (" + hd.lead + ")" + "</span></a><p>\n");
	}
	
	void writeAllLines(HtDirGetIt getIt) throws IOException
	{
		int num=0;
		BufferedWriter out = null;
		char newType, prevType = '*';
		int i;

		for (i=0; i<folderNumber; i++) {
		
			HtDir hd = htDirs[i];
			if ( hd == null ) break;

			newType = getIt.getType(hd);
            //System.out.println(newType);

			if ( newType != prevType ){
			
				if (out != null) {
					writeFootAndClose(out, i, num%5);
				}
				
				//System.out.println(getIt.getFileName(hd));
				out = new BufferedWriter(new FileWriter(rootDir + '/' + htDirName + '/' + getIt.getFileName(hd), false));
				writeHeader(out, htDirs[i], getIt);
				num = 0; // reset number for new type
				prevType = newType;
			}
					
			num++;

			if ( num % 5 == 1 ){
                if (i>0){
                    out.write("</tr></table>\n");
                }
                out.write("<table border=\"2\" cellpadding=\"5\" cellspacing=\"0\"><tr>\n");
			}
			
			write1stLine(out, hd);

			if ( num % 5 == 0 ){
				write2ndLines(out, i+1, 5);
			}
		}
		
		if ( out != null ){
			writeFootAndClose(out, i, num%5);
		}
	}

    void writeNameFiles() throws IOException
    {
		sortByName();
		groupHtDirs(new HtDirGetItName());
        writeAllLines(new HtDirGetItName());
    }

	void writeScoreFiles() throws IOException
	{
		sortByScore();
		groupHtDirs(new HtDirGetItScore());
        writeAllLines(new HtDirGetItScore());
	}

    boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

	void cleanUpCloset(String htmlDirName)
	{
		File f = new File(htmlDirName);
		// delete old stuff
		deleteDir(f);
	}

    void startMoveIn(String htmlDirName) throws IOException
    {
        File f = new File(htmlDirName);
        f.mkdir();
		CopyFile("index_n.htm");
		CopyFile("head_n.htm");
		CopyFile("index_s.htm");
		CopyFile("head_s.htm");
		CopyFile("hmake.css");
		CopyFile("star.gif");
		CopyFile("star5s.gif");
		CopyFile("star4s.gif");
		CopyFile("star3s.gif");
		CopyFile("star2s.gif");
		CopyFile("star1s.gif");
		CopyFile("star0s.gif");
    }
	
	void groupHtDirs(HtDirGetIt getIt)
	{
		int num=0, count=0;
		char newType, prevType = '*';

		for (int i=0; i<folderNumber; i++) {
		
			HtDir hd = htDirs[i];
			if ( hd == null ) break;

			newType = getIt.getType(hd);
			
			if ( newType != prevType ){
				htDirs[num].lead = count;
				num = i;
				count = 1;
				prevType = newType;
			}
			else{
				count++;
			}
		}
		htDirs[num].lead = count;
	}
	
	void CopyFile(String file) throws IOException{
	
		InputStream in  = getClass().getResourceAsStream("rc/" + file);
		//System.out.println(rootDir + '/' + htDirName + '/' + file);
		OutputStream out = new FileOutputStream(new File(rootDir + '/' + htDirName + '/' + file));
		
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0){
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
		//System.out.println("File copied.");
	}
	
	public void make(String dirName) {
		try {
	
		rootDir = dirName;

        cleanUpCloset(rootDir+'/'+htDirName);

        File dir = new File(rootDir);

        FileFilter filter = new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isDirectory() && pathname.getName().compareToIgnoreCase(htDirName)!=0;
                //return pathname.isDirectory();
			}
        };

        File[] files = dir.listFiles(filter);
		folderNumber = files.length;
		noThumbFolderNumber = 0;

        for (int i=0; i<files.length; i++) {
            System.out.println("[D] : " + files[i].getName());
			htDirs[i] = new HtDir(files[i]);
			if (!htDirs[i].hasThumb) noThumbFolderNumber++;
        }

        startMoveIn(rootDir+'/'+htDirName);

		writeNameFiles();
		OutputAsText();
		writeScoreFiles();
		
		} catch (IOException e) {}
	}
	
	public void OutputAsText () throws IOException
	{
			BufferedWriter	out = new BufferedWriter(new FileWriter(rootDir + '/' + htDirName + '/' + "DirList.txt"));
			for (int i=0; i<folderNumber; i++) {
				out.write(htDirs[i].dir + '\n');
			}
			out.close();
	}
	/*
	public String[] getStringArray()
	{
		ArrayList<String> tmp = new ArrayList<String>();
		for (int i=0; i<folderNumber; i++) {
			tmp.add(rootDir+'\\'+htDirs[i].dir);
		}
		
		String sa[] = new String[tmp.size()];
		sa = tmp.toArray(sa);
		return sa;
	}
	*/

}




